﻿using BZ.Logger;
using NDK.Module.Model;
using NDK.Motion.BLL;
using NDK.Motion.StationLogic;
using NDK.Motion.Sys;
using System;
using System.Threading;
using System.Windows.Forms;
using NDK.Module.DAL;
using System.IO;
using System.Diagnostics;
using NDK.Motion.MachineResources;
using NDK.Utils;
using System.Text;

namespace NDK.Module.StationLogic
{
    /// <summary>
    /// 继承工站抽象类，根据需求可重写相关函数
    /// </summary>
    public abstract class StationLogicBase : StationLogicAbstract
    {
        string _cyErrMsg;
        public string CyErrMsg
        {
            get { return _cyErrMsg + " 气缸动作超时，请检查！"; }
            set { _cyErrMsg = value; }
        }

        string _vcErrMsg;
        public string VcErrMsg
        {
            get { return _vcErrMsg + " 真空负压值未达到，请检查！"; }
            set { _vcErrMsg = value; }
        }

        protected DateTime dtCt = DateTime.Now;

        protected string logCtStr = string.Empty;
        protected string logBaseInfo = string.Empty;

        public const string CyTimeOutSolution = "\n1.检查气缸是否动作\n2.检查传感器\n3.检查接线";
        public const string CyOkTip = "点击OK按钮尝试继续运行";
        public const string CyCancelTip = "点击Cancel按钮忽略此报警继续运行[需确保安全]";

        public const string VcTimeOutSolution = "\n1.检查物料是否放平放正\n2.是否有负压，气管是否堵塞\n3.检查接线";
        public const string VcOkTip = "点击OK按钮尝试继续运行";
        public const string VcCancelTip = "点击Cancel按钮忽略此报警继续运行[需确保安全]";

        public DialogResult dr;
        public bool cyRes = false;
        public bool axRes = false;
        public bool lightRes = false;

        public bool camRes = false;

        protected string CT(DateTime dt_start)
        {
            return $"{Name}: [CT]->{(DateTime.Now - dt_start).TotalSeconds:0.000}s";
        }

        protected void WriteInferenceCT(string dir, string item, string res, string ct)
        {
            var path = Path.Combine(dir, "InferenceCT.txt");
            using (var sw = new StreamWriter(path))
            {
                sw.WriteLine($"item -> {res} -> {ct}");
            }
        }

        private static readonly object writeCTlogLock = new object();
        protected void WriteStationCTLog(string fileName, string strLog)
        {
            lock (writeCTlogLock)
            {
                string System_Now_Time = null;
                string File_Create_Time = null;

                System_Now_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"); //"HH:mm:ss
                File_Create_Time = DateTime.Now.ToString("yyyyMMdd");
                string logDocument = logBaseInfo + ".txt";

                string str = $"{Application.StartupPath}\\Log\\{fileName}\\{File_Create_Time}";
                if (!Directory.Exists(str))
                {
                    Directory.CreateDirectory(str);
                }
                str = str + "//" + logDocument;
                FileStream fs = new FileStream(str, FileMode.Append);
                StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                sw.WriteLine(System_Now_Time + ":   " + strLog);
                sw.Flush();
                sw.Close();
                fs.Close();
            }
        }

        /// <summary>
        /// 机台报警暂停
        /// </summary>
        /// <param name="title">弹框报警的标题</param>
        /// <param name="exMsg">异常信息</param>
        /// <param name="exSolution">可能的异常原因,及解决方案</param>
        /// <param name="okOperationTip">点击OK的操作意义</param>
        /// <param name="cancelOperationTip">点击Cancel的操作意义</param>
        /// <returns>返回用户操作结果</returns>
        protected override DialogResult AlarmPause(string title, string excMsg, string exSolution, string okOperationTip, string cancelOperationTip)
        {
            MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;
            Common.AppendUiLog.Log(excMsg + exSolution, LogType.Error);
            DateTime startTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            DialogResult dr = MessageBox.Show(excMsg + Environment.NewLine
                + "【原因(解决方案)】" + exSolution + Environment.NewLine
                + "【确定】" + okOperationTip + Environment.NewLine
                + "【取消】" + cancelOperationTip, title, MessageBoxButtons.OKCancel);

            if (dr == DialogResult.OK)
            {
                excMsg += ",点击【确定】" + okOperationTip;
            }
            else
            {
                excMsg += ",点击【取消】" + cancelOperationTip;
            }


            DateTime endTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            int timeCount = (endTime - startTime).Seconds;

            //if (Common.BP_UPMES)
            //{
            //    Common.SwMes.StatusDataUpload(STATUSCODE.报警中, startTime.ToString("yyyy-MM-dd HH:mm:ss"), endTime.ToString("yyyy-MM-dd HH:mm:ss"), "100105" + "");
            //}
            var time = DateTime.Now;
            string CSVDataDirectory = $"{Common.dataSavePath}\\{Common.ProjectName}\\{time:yyyy-MM}\\{Common.CurProType} Data\\{time:yyyy-MM-dd}";
            if (!Directory.Exists(CSVDataDirectory))
            {
                Directory.CreateDirectory(CSVDataDirectory);
            }
            string fullPath = $"{CSVDataDirectory}\\报警上传记录" + DateTime.Now.ToString("yyyy-MM-dd") + ".csv";
            var strs = $"{excMsg}" + "_" + "开始时间" + startTime + "," + "结束时间" + endTime + "," + "100105" + "";
            FileUtils.AppendText(fullPath, strs + "\r\n");
            AlarmInfo alarmInfo = new AlarmInfo()
            {
                StartTime = startTime,
                EndTime = endTime,
                TimeCount = timeCount,
                Type = title,
                Description = excMsg
            };
            AlarmInfoServices AlarmInfoServices = new AlarmInfoServices();
            AlarmInfoServices.Add(alarmInfo);

            return dr;
        }
        protected override DialogResult AlarmPause(string title, string excMsg, string exSolution, string okOperationTip)
        {
            MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;

            Common.AppendUiLog.Log(excMsg + exSolution, LogType.Error);

            DateTime startTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            DialogResult dr = MessageBox.Show(excMsg + Environment.NewLine
               + "【原因(解决方案)】" + exSolution + Environment.NewLine
               + "【确定】" + okOperationTip + Environment.NewLine,
               title, MessageBoxButtons.OK);

            if (dr == DialogResult.OK)
            {
                excMsg += ",点击【确定】" + okOperationTip;
            }

            DateTime endTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            int timeCount = (endTime - startTime).Seconds;
            var time = DateTime.Now;
            string CSVDataDirectory = $"{Common.dataSavePath}\\{Common.ProjectName}\\{time:yyyy-MM}\\{Common.CurProType} Data\\{time:yyyy-MM-dd}";
            if (!Directory.Exists(CSVDataDirectory))
            {
                Directory.CreateDirectory(CSVDataDirectory);
            }
            string fullPath = $"{CSVDataDirectory}\\报警上传记录" + DateTime.Now.ToString("yyyy-MM-dd") + ".csv";
            var strs = $"{excMsg}" + "_" + "开始时间" + startTime + "," + "结束时间" + endTime + "," + "100105" + "";
            FileUtils.AppendText(fullPath, strs + "\r\n");

            AlarmInfo alarmInfo = new AlarmInfo()
            {
                StartTime = startTime,
                EndTime = endTime,
                TimeCount = timeCount,
                Type = title,
                Description = excMsg
            };
            AlarmInfoServices AlarmInfoServices = new AlarmInfoServices();
            AlarmInfoServices.Add(alarmInfo);
            return dr;
        }
        protected override DialogResult AlarmPause(string title, string excMsg, string exSolution, string yesOperationTip, string noOperationTip, string cancelOperationTip)
        {
            MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;
            Common.AppendUiLog.Log(excMsg + exSolution, LogType.Error);

            DateTime startTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            DialogResult dr = MessageBox.Show(excMsg + Environment.NewLine
                + "【原因(解决方案)】" + exSolution + Environment.NewLine
                + "【是】" + yesOperationTip + Environment.NewLine
                + "【否】" + noOperationTip + Environment.NewLine
                + "【取消】" + cancelOperationTip,
                title, MessageBoxButtons.YesNoCancel);

            if (dr == DialogResult.Yes)
            {
                excMsg += ",点击【是】" + yesOperationTip;
            }
            else if (dr == DialogResult.No)
            {
                excMsg += ",点击【否】" + noOperationTip;
            }
            else
            {
                excMsg += ",点击【取消】" + cancelOperationTip;
            }

            DateTime endTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            int timeCount = (endTime - startTime).Seconds;

            AlarmInfo alarmInfo = new AlarmInfo()
            {
                StartTime = startTime,
                EndTime = endTime,
                TimeCount = timeCount,
                Type = title,
                Description = excMsg
            };

            AlarmInfoServices AlarmInfoServices = new AlarmInfoServices();
            AlarmInfoServices.Add(alarmInfo);

            return dr;
        }

        protected void UILog_Info(string mes)
        {
            Common.AppendUiLog.Log(mes, LogType.Info);
        }
        protected void UILog_Alert(string mes)
        {
            Common.AppendUiLog.Log(mes, LogType.Alert);
        }
        protected void UILog_Error(string mes)
        {
            Common.AppendUiLog.Log(mes, LogType.Error);
        }
    }
}
